const https = require('https');
//雪花算法生成id
const snowflake = require('./Snowflake')
let SQLHelp = require('./SQLHelp');
const {formatTime} = require('./util')

module.exports = function(app){
    //登录拦截中间件
    function loginRouter(req,res,next){
        let token = req.headers.token
        if(token){
            SQLHelp(`select * from session where id = ${token}`).then(ret => {
                if(ret.length){
                    let session = ret[0]
                    req.session = {
                        userId:session.userId,
                        userName:session.userName
                    }
                    next()
                }else{
                    res.status(406).send({errorMsg:'当前用户未登录'})
                } 
            })
        }else{
            res.status(405).send({errorMsg:'缺少token,请先进行登录'})
        }
        
    }
    //让初登陆以为的所有小程序接口都先验证登录
    app.use('/wx',loginRouter)
    

    //获取openid
    app.get('/wxlogin',(req,res,next) => {
        let code = req.query.code
        console.log(req.query)
        let appid = 'wx854246b950cc005c'
        let secret ='4517260d4571c665ed799570c5bd62d0'
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`,(ret) => {
            ret.on('data',(ret)=>{
                ret = JSON.parse(ret.toString())
                let openid = ret.openid
                if(!openid){
                    res.send({errorMsg:ret.errMsg || '获取openid错误'})
                }else{
                    
                    SQLHelp(`select * from member where openId = '${openid}'`).then(memRet => {
                        if(memRet.length){
                            req.member = memRet[0]
                            next()
                            
                        }//用户已存在
                        else{
                            SQLHelp(`insert into member(openId) value ('${openid}')`).then(memRet => {
                                SQLHelp(`select * from member where openId = '${openid}'`).then(memRet => {
                                    req.member = memRet[0]
                                    next()
                                })
                            })
                        }
                    })
                }
            });
        }).on('error',(e)=>{
            console.error(e)
            res.send({errorMsg:'获取openid错误'})
        });
    },(req,res) => {
        let token = snowflake()
        let member = req.member
        SQLHelp(`
        insert into session(id,userId,userName,inTime,platform)
        values ('${token}','${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
        `).then(ret => {
            res.send({
            nickName:member.nickName,
            token,
            openId:member.openId,
            avatarUrl:member.avatarUrl,
            _id:member._id
        })
        })
        
    })
    //修改用户头像和昵称
    app.put('/wx/member',(req,res) => {
        let userInfo = req.body
        SQLHelp(`
        update member
        set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
        where _id = '${req.session.userId}'
        `).then(ret => {
            console.log(ret)
            res.send({})
            })
    })
    //获取地址列表
    app.get('/wx/address',loginRouter,(req,res) => {
        if(req.session.userId){
            SQLHelp(`select * from address where state = 1 and memberId = '${req.session.userId}'`).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'请传入memberId'})
        }
    })
    //新增地址
    app.post('/wx/address',(req,res) => {
        if(req.session.userId && req.body.receiver && req.body.phone && req.body.city){
            SQLHelp(`
            insert into address(state,memberId,receiver,phone,city,area)
            values (1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area}')
            `).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //设置默认地址
    app.put('/wx/address/default',(req,res) => {
        let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault == 1 ? 1 : 0
        if(addressId && memberId){
            if(isDefault == 1){
                SQLHelp(`
                update address set isDefault = 0 where isDefault = 1 and memberId = ${memberId}
                `).then(ret => {
                    SQLHelp(`
                    update address set isDefault = 1 where _id = ${addressId}
                    `).then(ret => {
                        res.send(ret)
                    })
                })
            }else{
                SQLHelp(`
                update address set isDefault = 0 where _id = ${addressId}
                `).then(ret => {
                    res.send(ret)
                })
            }
            
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //删除地址
    app.delete('/wx/address',(req,res) => {
        let addressId = req.body.addressId
        if(addressId){
            SQLHelp(`
            update address
            set state = 0
            where _id = '${addressId}'
            `).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
    //获取详情地址
    app.get('/wx/address/detail',(req,res) => {
        if(req.query.addressId){
            SQLHelp(`select * from address where _id = '${req.query.addressId}'`).then(ret => {
                res.send(ret.length ? ret[0] : {errorMsg:'未获取到地址详情'})
            })
        }else{
            res.send({errorMsg:'请传入addressId'})
        }
    })
    //修改地址详情
    app.put('/wx/address',(req,res) => {
        let addressId = req.body.addressId
        if(addressId){
            let updatekey = ['receiver','phone','city','area']
            let updatevalues = []
            for(let i = 0;i < updatekey.length;i++){
                let key = updatekey[i],value = req.body[key]
                if(value) updatevalues.push(`${key}='${value}'`)
            }
            SQLHelp(`update address set ${updatevalues.join(',')} where _id = '${addressId}'`).then(ret => {
                res.send(ret)
            }) 
        }else{
            res.send({errorMsg:'传入参数错误'})
        }   
    })
    

}